package com.tanhua.admin.listener;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.db.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @auther : 白月尘
 * @date : 14:41  2021/10/28
 */
@Component
public class AuditListener {
    @Autowired
    private AliyunGreenTemplate template;

    @DubboReference
    private MovementApi movementApi;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "tanhua.audit.queue"),
                    exchange = @Exchange(value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC),
                    key = "audit.movement"
            )
    )
    public void log(String message) throws Exception {
        Movement movement = movementApi.findById(message);
        if (movement != null && movement.getState() == 0) {
            List<String> medias = movement.getMedias();
            String textContent = movement.getTextContent();
            Map<String, String> textScan = template.greenTextScan(textContent);
            Map<String, String> imageScan = template.imageScan(medias);
            if (textScan != null && imageScan != null) {
                int state = 0;
                if ("block".equals(textScan.get("suggestion")) || "block".equals(imageScan.get("suggestion"))) {
                    state = 2;
                } else if ("pass".equals(textScan.get("suggestion")) && "pass".equals(imageScan.get("suggestion"))) {
                    state = 1;
                }
                if (state != 0) {
                    movementApi.updateState(message, state);
                }
            }
        }
    }
}
